package handlers

import (
	"dha/app/models"
	"dha/pub"
	"io"
	"strconv"

	"github.com/gin-gonic/gin"
)

func GetConfig(c *gin.Context) {
	name := c.Param("name")

	var pageInfo = new(models.PageInfo)

	err := pub.DB().
		Where("name=?", name).
		First(pageInfo).Error

	if pub.ReqErr(c, err, "获取配置信息失败") {
		return
	}

	pub.Resp(c, pageInfo)
}

func AddConfig(c *gin.Context) {
	name := c.Param("name")

	body, err := io.ReadAll(c.Request.Body)
	if pub.ReqErr(c, err, "获取数据失败") {
		return
	}

	var pageInfo = &models.PageInfo{}

	pub.DB().Where("name=?", name).First(pageInfo)

	pageInfo.Name = name
	pageInfo.Content = string(body)

	err = pub.DB().Save(pageInfo).Error
	if pub.ReqErr(c, err, "新增失败") {
		return
	}

	pub.Resp(c, nil, "新增成功")
}

func ConfigList(c *gin.Context) {
	pageStr := c.Param("page")
	perPageStr := c.Param("perPage")

	page, err := strconv.ParseInt(pageStr, 10, 64)
	if pub.ReqErr(c, err, "页码错误") {
		return
	}

	perPage, err := strconv.ParseInt(perPageStr, 10, 64)
	if pub.ReqErr(c, err, "页码错误") {
		return
	}

	var res = []*models.PageInfo{}

	err = pub.DB().Limit(int(perPage)).
		Offset(int((page - 1) * perPage)).
		Order("created_at desc").
		Find(&res).Error
	if pub.ReqErr(c, err, "获取配置信息失败") {
		return
	}

	pub.Resp(c, res)
}
